//
//  ZImageLoopView.m
//
//  Created by 周成龙
//

#import "ZImageLoopView.h"

@interface ZImageLoopView () <UIScrollViewDelegate>

/**
 内部scrollView
 */
@property (nonatomic, strong) UIScrollView *scrollView;

/**
 每页的大小
 */
@property (nonatomic, assign) CGSize pageSize;

/**
 存放containerView的数组
 */
@property (nonatomic, strong) NSMutableArray *containerViews;

/**
 当前显示页的index
 */
@property (nonatomic, assign) NSInteger currentPageIndex;

/**
 自动轮播定时器
 */
@property (nonatomic, weak) NSTimer *timer;

/**
 轮播图片总页数
 */
@property (nonatomic, assign) NSInteger pageCount;

@end

@implementation ZImageLoopView

#pragma mark - 初始化
- (instancetype)initWithFrame:(CGRect)frame withDataSource:(id<ZImageLoopViewDataSource>)dataSource withDelegate:(id<ZImageLoopViewDelegate>)delegate {
    self = [super initWithFrame:frame];
    if (self) {
        _dataSource = dataSource;
        _delegate = delegate;
        [self initialize];
        [self setupUI];
        [self startScroll];
    }
    return self;
}

- (void)initialize {
    self.pageSize = self.bounds.size;
    self.second = 3;
    _currentPageIndex = 0;
    self.containerViews = [NSMutableArray array];
    
    self.scrollView = [[UIScrollView alloc] initWithFrame:self.bounds];
    self.scrollView.scrollsToTop = NO;
    self.scrollView.delegate = self;
    self.scrollView.pagingEnabled = YES;
    self.scrollView.clipsToBounds = NO;
    self.scrollView.showsHorizontalScrollIndicator = NO;
    self.scrollView.showsVerticalScrollIndicator = NO;
    [self addSubview:self.scrollView];
}

- (void)setupUI {
    if (_dataSource && [_dataSource respondsToSelector:@selector(numberOfPagesInLoopView:)]) {
        self.pageCount = [_dataSource numberOfPagesInLoopView:self];
        if (self.pageCount == 0) {
            return;
        }
    }
    
    // 重置pageWidth
    if (_delegate && [_delegate respondsToSelector:@selector(sizeForPageInLoopView:)]) {
        _pageSize = [_delegate sizeForPageInLoopView:self];
    }
    
    // 重置_scrollView的contentSize
    _scrollView.frame = CGRectMake((self.bounds.size.width - _pageSize.width) / 2, 0, _pageSize.width, _pageSize.height);
    _scrollView.contentSize = CGSizeMake(_pageSize.width * 5, _pageSize.height);
    
    // 创建5个ZContainerView容器
    for (ZContainerView *view in _scrollView.subviews) {
        [view removeFromSuperview];
    }
    [_containerViews removeAllObjects];
    for (NSInteger i = 0; i < 5; i++) {
        ZContainerView *containerView = [[ZContainerView alloc] initWithFrame:CGRectMake(i * _pageSize.width, 0, _pageSize.width, _pageSize.height)];
        containerView.tag = i + 10;
        [_containerViews addObject:containerView];
        [_scrollView addSubview:containerView];
        
        if ([_dataSource respondsToSelector:@selector(loopView:cellForPageAtIndex:)]) {
            ZLoopCell *cell = [_dataSource loopView:self cellForPageAtIndex:((_currentPageIndex + i - 2) + _pageCount) % _pageCount];
            cell.frame = containerView.bounds;
            [containerView.containerView addSubview:cell];
        }
    }
    
    // 滚动到中间的containerView
    _scrollView.contentOffset = CGPointMake(_pageSize.width*2, 0);
}

#pragma mark - 定时器
- (void)startScroll {
//    self.timer = [NSTimer scheduledTimerWithTimeInterval:self.second target:self selector:@selector(autoNextPage) userInfo:nil repeats:YES];
//    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}

- (void)stopScroll {
    [self.timer invalidate];
    self.timer = nil;
}

- (void)autoNextPage {
    [_scrollView setContentOffset:CGPointMake(3*_pageSize.width, 0) animated:YES];
}

#pragma mark - 刷新数据
- (void)reloadData {
    [self stopScroll];
    [self setupUI];
    [self startScroll];
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView == self.scrollView) {
        if (_pageCount == 0) {
            return;
        }
        
        // 向手指向右滑动
        if (_scrollView.contentOffset.x <= _pageSize.width) {
            [self stopScroll];
            // 删除最后的一个 cell
            [_containerViews.lastObject removeFromSuperview];
            [_containerViews removeLastObject];
            
            // 将剩下的cell都向右移动一个cell宽度的位置
            for (NSInteger i = 0; i < _containerViews.count; i ++) {
                ZContainerView *containerView = _containerViews[i];
                containerView.frame = CGRectMake((i + 1) * _pageSize.width, 0, _pageSize.width, _pageSize.height);
                containerView.tag = i + 1 + 10;
            }
            
            // 前面添加一个 cell
            ZContainerView *containerView = [[ZContainerView alloc] initWithFrame:CGRectMake(0 * _pageSize.width, 0, _pageSize.width, _pageSize.height)];
            containerView.tag = 0 + 10;
            [_containerViews insertObject:containerView atIndex:0];
            [_scrollView addSubview:containerView];
            ZLoopCell *cell = [_dataSource loopView:self cellForPageAtIndex:(_pageCount + (_currentPageIndex - 1 - 2)) % _pageCount];
            cell.frame = containerView.bounds;
            [containerView.containerView addSubview:cell];
            
            // 重新滚动到中间的 containerView
            _scrollView.contentOffset = CGPointMake(_pageSize.width * 2, 0);
            // 更新 _currentPageIndex 位置
            if ([_delegate respondsToSelector:@selector(loopView:didScrollToPage:)]) {
                _currentPageIndex = (_pageCount + (_currentPageIndex - 1)) % _pageCount;
                [_delegate loopView:self didScrollToPage:_currentPageIndex];
            }
            [self startScroll];
        }
        
        // 手指向左滑动
        if (_scrollView.contentOffset.x >= _pageSize.width * 3) {
            [self stopScroll];
            // 删除最前面的一个 cell
            [_containerViews.firstObject removeFromSuperview];
            [_containerViews removeObjectAtIndex:0];
            
            // 将剩下的cell都向左移动一个cell宽度的位置
            for (NSInteger i = 0; i < _containerViews.count; i ++) {
                ZContainerView *containerView = _containerViews[i];
                containerView.frame = CGRectMake(i * _pageSize.width, 0, _pageSize.width, _pageSize.height);
                containerView.tag = i + 10;
            }
            
            // 最后添加一个 cell
            ZContainerView *containerView = [[ZContainerView alloc] initWithFrame:CGRectMake(4 * _pageSize.width, 0, _pageSize.width, _pageSize.height)];
            containerView.tag = 4 + 10;
            [_containerViews addObject:containerView];
            [_scrollView addSubview:containerView];
            // 这里使用 _currentPageIndex + 1 + 2 是因为 此时 _currentPageIndex 还未更新为最新的，_currentPageIndex + 1 为最新的位置，之后的第二个位置添加
            ZLoopCell *cell = [_dataSource loopView:self cellForPageAtIndex:(_currentPageIndex + 1 + 2) % _pageCount];
            cell.frame = containerView.bounds;
            [containerView.containerView addSubview:cell];
            
            // 重新滚动到中间的 containerView
            _scrollView.contentOffset = CGPointMake(_pageSize.width * 2, 0);
            // 更新 _currentPageIndex 位置
            if ([_delegate respondsToSelector:@selector(loopView:didScrollToPage:)]) {
                _currentPageIndex = (_currentPageIndex + 1) % _pageCount;
                [_delegate loopView:self didScrollToPage:_currentPageIndex];
            }
            
            [self startScroll];
        }
    }
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    if (scrollView == self.scrollView) {
        [self stopScroll];
    }
}
@end
